<?php
/************************************
*   新浪相册 7.0
*   @file:lib_memcached.php
*   @intro:
*   @author:shaopu@
*   @date:Mon Nov 24 16:00:30 CST 2008
************************************/

class lib_memcache
{
    private $_config = array();     //mc配置
    private $_mc;                   //memcached实例
    private $is_compress = false;
    
    public function __construct($config , $is_compress = false)
    {
        $this->_mc = new memcache();
        $this->is_compress = $is_compress;
        
        
        $this->_config = $config;
        list($host , $port) = explode(':' , $config[0]);
        $this->_mc->connect($host , $port);
    }
    
    /**
     * 记出错LOG,只用作调试
     *
     * @param 当前调用的方法名 $func
     * @param string $content
     * @return true
     */
    private function _log($func , $content)
    {
        K_log::debug(__CLASS__ , $func .TAB. $content);
        return true;
    }

    /**
     * 取一条记录
     *
     * @param string $key   键   
     * @param mix $value
     * @return bool
     */
    public function get($key , &$value)
    {
        $value = $this->_mc->get( $key);
        return $value === false ? false : true;
    }
    
    /**
     * 取多条记录
     *
     * @param array $aKeys  多个键
     * @param mix $value
     * @param string $hash_key  哈希服务器用　常用UID　
     * @return bool 
     */
    public function get_multi($aKeys , &$value)
    {
        if(!is_array($aKeys))
            return false;

        $value = $this->_mc->get($aKeys);
        return true;
    }
    
    /**
     * 设置一条记录
     *
     * @param string $key
     * @param mix $value
     * @param int $expire sec
     * @return bool
     */
    public function set($key , $value , $expire = 0)
    {
        
        $rs = $this->_mc->set($key , $value , $this->is_compress , $expire);
            
        return $rs;
    }
    
    /**
     * 删除一条记录
     *
     * @param string $key
     * @return bool
     */
    public function delete($key)
    {
        $rs = $this->_mc->delete($key);
        return $rs;
    }
    
    
    
    /**
     * 累加操作
     *
     * @param string $key
     * @param int $n
     * @return bool
     */
    public function increment($key , $n = 1)
    {
        if(!$this->_mc->increment($key , (int)$n))//没有则创建
        {
            return $this->_mc->set($key , $n);
        }
    }
    
    /**
     * 递减操作
     *
     * @param string $key
     * @param int $n
     * @return bool
     */
    public function decrement($key , $n = 1)
    {
        $rs = $this->_mc->decrement($key , (int)$n);

        return $rs;
    }
    
}
?>